﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using RuoVea.ExDto;
using RuoVea.ExDto.Language;
using RuoVea.ExEnum;
using RuoVea.ExIdGen;
using RuoVea.ExSugar;
using RuoVea.ExUtil;

namespace RuoVea.H5ds.Web.Controllers;

[Authorize(Roles = "None")]
public partial class H5DSDataController : Controller
{
    /// <summary>
    /// 
    /// </summary>
    private readonly SugarRepository<H5Template> _thisRepository;
    private readonly SugarRepository<H5PageData> _dataServer;
    private readonly ICurrentUser _currentUser;

    /// <summary>
    /// 
    /// </summary>
    /// <param name="thisRepository"></param>
    /// <param name="currentUser"></param>
    /// <param name="dataServer"></param>
    public H5DSDataController(SugarRepository<H5Template> thisRepository, ICurrentUser currentUser, SugarRepository<H5PageData> dataServer)
    {
        _thisRepository = thisRepository;
        _currentUser = currentUser;
        _dataServer = dataServer;
    }

    public IActionResult Index(string appId)
    {
        ViewBag.appId = appId;
        return View();
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpGet("H5DSData/data/{id:long}")]
    public async Task<RestfulResult<H5Template>> GetDataAsync(long id)
    {
        RestfulResult<H5Template> restful = new() { Code = CodeStatus.BadRequest };

        if (id == 0)
        {
            restful.Message = "失败";
            return restful;
        }

        H5Template temp = await _thisRepository.GetFirstAsync(x => x.Id == id);
        if (temp == null||string.IsNullOrWhiteSpace(temp.Content))
        {
            restful.Message = "请先预设模板(模板设计)";
            return restful;
        }

        var pageData = await _dataServer.AsQueryable().Where(x => x.TempId == id&&x.IsDisable== YesOrNot.N).ToListAsync();

        if (pageData == null || pageData.Count == 0)
        {
            restful.Message = "请先预设至少一条模板数据";
            return restful;
        }

        Project project = temp.Content.ToObject<Project>();
        if (project == null)
        {
            restful.Message = "请先预设模板(模板设计)";
            return restful;
        }
        Page tempPage = project.pages.FirstOrDefault();

        if (tempPage == null)
        {
            restful.Message = "模板至少预设一个内容";
            return restful;
        }

        foreach (var iFixed in project.fixeds)
        {
            iFixed.keyid = IdGenerator.IdStr("fixed");
        }

        var settings = new JsonSerializerSettings
        {
            DefaultValueHandling = DefaultValueHandling.Ignore,
            NullValueHandling = NullValueHandling.Ignore
        };

        if (temp.ResultContent.IsNullOrWhiteSpace())
        {
            List<Page> Pages = new List<Page>();
            foreach (var item in pageData)
            {
                project = temp.Content.ToObject<Project>();
                tempPage = project.pages.FirstOrDefault();
                Page minPage = new Page() { keyid = item.Id.ToString() };
                minPage.layers = ReplacePlaceholders(tempPage.layers, item);
                minPage.style = tempPage.style;
                minPage.slider = tempPage.slider;
                Pages.Add(minPage);
            }
            project.pages = Pages;

            temp.Content = "";
            temp.ResultContent = JsonConvert.SerializeObject(project, settings);
        }
        else 
        {
            Project resultProject = temp.ResultContent.ToObject<Project>();
            var ids = resultProject.pages.Select(x => x.keyid).ToList();

            var needData = pageData.Where(x => !ids.Contains(x.Id.ToString()));
            List<Page> needPages = new List<Page>();
            if (needData.Any()) 
            {
                foreach (var item in needData)
                {
                    project = temp.Content.ToObject<Project>();
                    tempPage = project.pages.FirstOrDefault();
                    Page minPage = new Page() { keyid = item.Id.ToString() };
                    minPage.layers = ReplacePlaceholders(tempPage.layers, item);
                    minPage.style = tempPage.style;
                    minPage.slider = tempPage.slider;
                    needPages.Add(minPage);
                }
                resultProject.pages.AddRange(needPages);


                temp.Content = "";
                temp.ResultContent = JsonConvert.SerializeObject(resultProject, settings);
            }
        }

        restful.Data = temp;
        restful.Code = CodeStatus.OK;
        return restful;
    }
    private List<Layer> ReplacePlaceholders(List<Layer> layers, H5PageData item)
    {
        string layersData = "";
        foreach (var layer in layers)
        {
            layersData = "";
            layersData = layer.data.data;

            layersData = layersData?.Replace("@value1", item.Value1)
               ?.Replace("@value2", item.Value2)
               ?.Replace("@value3", item.Value3)
               ?.Replace("@value4", item.Value4)
               ?.Replace("@value5", item.Value5);

            layer.data.data = layersData;
            layer.keyid = IdGenerator.IdStr("layer");
        }
        return layers;
    }
    /// <summary>
    /// 修改
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    [HttpPost("H5DSData/submit")]
    public async Task<RestfulResult> SubmitAsync([FromBody] H5Template data)
    {
        RestfulResult restful = new() { Code = CodeStatus.BadRequest };

        var isExist = await _thisRepository.IsAnyAsync(u => u.Id == data.Id /*&& u.Creator == _currentUser.UserId*/);
        if (!isExist)
        {
            restful.Message = ErrorEnum.D3000.GetDescription(i18n.ResourceManager);
            return restful;
        }
        bool result = await _thisRepository.UpdateAsync(data);
        if (result)
        {
            restful.Data = result;
            restful.Code = CodeStatus.OK;
            return restful;
        }
        else
        {
            restful.Message = "修改失败";
            return restful;
        }
    }
}

